package com.esiag.loadbalancer.main;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

import com.esiag.pdsteam.entity.IEntity;

public class Entity extends Thread implements IEntity<String>{
	private static final long serialVersionUID = 1L;

	private String mName;
	private List<String> mNames = Collections.synchronizedList(new ArrayList<String>());
	
	
private static Logger logger = Logger.getLogger("LoadBalancingTest");
	
	public Entity() {
		FileHandler fileHandler;
		try {
			fileHandler = new FileHandler("GhitahJabri.log");
			logger.addHandler( fileHandler);
			SimpleFormatter formatter = new SimpleFormatter();  
	        fileHandler.setFormatter(formatter);  
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public Entity(String pName) {
		mName = pName;
		start();
	}
	
	public boolean isBest(IEntity<String> pEntity) {
		if(!(pEntity instanceof Entity)){
			return false;
		}
		Entity entity = (Entity)pEntity;
		return entity.mNames.size() < mNames.size();
	}
	
	public void sendInfo(String pInfo) {
		synchronized (mNames) {
			mNames.add(pInfo);	
		}
	}
	
	@Override
	public void run() {
		while(true){
			try{
				synchronized (mNames) {
					if(mNames.size() > 0){
						logger.log(Level.INFO, mName + " (" + mNames.size() +  ")" + mNames.remove(0));
		

					}
				}
				int random = (int)(Math.random() * (1000));
				Thread.sleep(random);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}
	
	public String toString() {
		return mName + ":" + mNames.size();
	}
}
